package com.baizhi.controller;

import com.baizhi.entity.Article;
import com.baizhi.service.ArticleService;
import com.baizhi.serviceplus.ArticleServicePlus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@Controller
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleServicePlus articleServicePlus;

    @RequestMapping("/selectArticle")
    @ResponseBody
    public Map selectArticle(Integer page,Integer limit){
        Map map = articleService.selectArticle(page,limit);
        return  map;
    }


    @RequestMapping("/deleteArticle")
    @ResponseBody
    public Map deleteArticle(Integer id){
        Map map = articleServicePlus.deleteArticle(id);
        return  map;
    }

    @RequestMapping("/insertArticle")
    @ResponseBody
    public Map insertArticle(MultipartFile file, Article article , HttpServletRequest request) throws IOException {
        System.out.println(article);
        //获取上传的绝对路径
        String realPath = request.getServletContext().getRealPath("/cmfz/img");
        //获取原文件名称
        String originalFilename = new Date().getTime()+"_"+file.getOriginalFilename();
        System.out.println(originalFilename);
      //上传到服务器
       file.transferTo(new File(realPath+"/"+originalFilename));

       //存入数据库的名称
        article.setArticleImage("/cmfz/img/"+originalFilename);
        System.out.println(article);
        Map map = articleServicePlus.insertArticle(article);
        return  map;
    }
    @RequestMapping("/updateArticle")
    @ResponseBody
    public Map updateArticle(MultipartFile file, Article article , HttpServletRequest request) throws IOException {

       if (!"".equals(file.getOriginalFilename())) {
           System.out.println(1212+file.getOriginalFilename()+2323);
           System.out.println(article);
           //获取上传的绝对路径
           String realPath = request.getServletContext().getRealPath("/cmfz/img");
           //获取原文件名称
           String originalFilename = new Date().getTime() + "_" + file.getOriginalFilename();
           System.out.println(originalFilename);
           //上传到服务器
           file.transferTo(new File(realPath + "/" + originalFilename));

           //存入数据库的名称
           article.setArticleImage("/cmfz/img/" + originalFilename);
           System.out.println(article);
       }
        System.out.println(article);
        Map map = articleServicePlus.updateArticle(article);
        return  map;
    }



}
